/**
 * @author Vitor Franco do Carmo (vfcarmo@gmail.com)
 * @since 31/10/2013
 *
 */
package br.com.vfcfw.persistence.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Classe utilitária responsável por criar e disponibilizar a fábrica de sessões do hibernate.
 * 
 * @author Vitor Franco do Carmo (vfcarmo@gmail.com)
 * @since 31/10/2013
 * 
 */
public class HibernateUtil {

    private static SessionFactory sessionFactory;

    private static ServiceRegistry serviceRegistry;

    /**
     * Retorna a fábrica de sessões do hibernate.
     * 
     * @return {@link SessionFactory}.
     */
    public static SessionFactory getSessionFactory() {

        if (sessionFactory == null) {

            configureSessionFactory();
        }
        return sessionFactory;
    }

    /**
     * Configura e retorna a fábrica de sessões do hibernate.
     */
    private static void configureSessionFactory() {

        Configuration configuration = new Configuration();
        configuration.configure();

        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
            .buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }
}
